import {defineStore} from 'pinia'
import {LoginService, OpenAPI, RString, RUserVo, UserService} from "/@/api/openapi";
import {ElMessage} from 'element-plus'
import {global} from "/@/config/global";
import {store} from "/@/store"
import {useRouter} from "vue-router";


// 定义状态的类型 一般情况下Pinia会自动推断出state的类型，你就无需定义接口。如果state的数据类型比较复杂，推荐你定义一个接口来描述state的类型
export interface IUserState {
    username: string,
    avatar: string,
    uid: number
    token: string
    isSign: boolean,
    signature: string,
    admin: string
}

export const useUserStore = defineStore("user", {
    state: (): IUserState => ({
        username: "",
        avatar: "",
        uid: 0,
        token: "",
        isSign: false,
        signature: "",
        admin: ""
    }),
    getters: {
        getToken(): string {
            return this.token
        },
        getUid(): number {
            return this.uid
        }
    },
    actions: {

        loginOut() {
            OpenAPI.TOKEN = ""
            this.token = "";
            this.avatar = "";
            this.isSign = false;
            localStorage.removeItem(global.USER)
            localStorage.removeItem(global.USERINFO)

        },
        initData: function () {
            const token = localStorage.getItem(global.USER);
            // 修改
            if (token !== null && token !== undefined && token !== '') {
                this.updateToken(token);
                this.updateUser(token);
            }
        },
        updateToken(token: string) {
            OpenAPI.TOKEN = token
            this.token = token
        },
        async updateUser(token: string): Promise<boolean> {
            // 获取用户信息
            const data = await UserService.queryById().then((res: RUserVo) => {
                console.log(res)
                if (res.data !== undefined) {

                    if (res.data.avatar !== undefined) {
                        this.avatar = res.data.avatar;
                    }
                    if (res.data.username !== undefined) {
                        this.username = res.data.username
                    }
                    if (res.data.id !== undefined) {
                        this.uid = res.data.id
                    }
                    if (res.data.signature !== undefined) {
                        this.signature = res.data.signature
                    }
                    if (res.data.userRole !== undefined) {
                        this.admin = res.data.userRole
                    }
                    localStorage.setItem(global.USERINFO, JSON.stringify(res.data))
                    this.isSign = true
                    return true;
                }

            }, (error: string) => {
                console.log(error)
                return false;
            }).catch(() => {
                return false;
            })
            if (data === undefined) {
                return false;
            }
            return data;
        },

        async login(username: string, password: string): Promise<boolean> {
            const information = {
                "username": username,
                "password": password
            }
            const data = await LoginService.login(information).then((res: RString) => {
                console.log(res)
                if (res.code === 200 && res.data !== undefined) {
                    ElMessage(
                        {
                            message: '登录成功' + res.data,
                            type: 'success',
                        }
                    )
                    localStorage.setItem(global.USER, res.data)
                    this.updateToken(res.data)
                    return this.updateUser(res.data);
                } else {
                    ElMessage.error(res.message)
                }
            }, (values: RString) => {
                console.log(values)
                return false;
            })
            if (data === undefined) {
                return false;
            }
            return data;
        }
    }
})

export function getUserStore() {
    return useUserStore(store)
}